from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends
from app.services.user_service import UserService
from app.redis_client import RedisSingleton

@asynccontextmanager
async def lifespan(app: FastAPI):
    yield  # 应用运行中
    await RedisSingleton.close()  # 关闭连接池

app = FastAPI(lifespan=lifespan)

# 依赖注入简化调用
async def get_user_service():
    return UserService

@app.get("/users/{user_id}")
async def get_user(
    user_id: str,
    service: UserService = Depends(get_user_service)
):
    data = await service.get_user(user_id)
    return {"data": data} if data else {"error": "User not found"}

@app.post("/users/{user_id}")
async def create_user(
    user_id: str,
    name: str,
    service: UserService = Depends(get_user_service)
):
    return await service.set_user(user_id, name)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run("main:app", host='127.0.0.1', port=8000, log_level="info", reload=True)
